//
//  LGAdviceMedicineController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/6/15.
//

#import "LGAdviceMedicineController.h"
//添加、编辑药物
#import "LGAddMedicineController.h"
#import "LGAdviceMedicineCell.h"
#import "LGAdviceRecordMedicineCell.h"
#import "LGMedicineSectionHeader.h"
@interface LGAdviceMedicineController ()<UITableViewDelegate,UITableViewDataSource>
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *addButton;
/**   */
@property (nonatomic , strong)NSArray *historyArray;

@end

@implementation LGAdviceMedicineController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    [self emptyViewWithSuperView:self.view frame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight)];
    self.emptyView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.addButton];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestData];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/medical_advice.medical_advice/getCurrentMedicine" parameters:@{@"patient_id":self.patientid,@"followup_id":self.followid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(code == 200){
            self.dataArray = returnData[@"advice"][@"content"];
            self.adviceid = LGNSString(returnData[@"advice"][@"advice_id"]);
            self.historyArray = returnData[@"history"];
            [self.tableView reloadData];
            if(self.delegate && [self.delegate respondsToSelector:@selector(observerSendStatus)]){
                [self.delegate observerSendStatus];
            }
        }
        if(self.dataArray.count == 0 && self.historyArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无数据" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(self.dataArray.count == 0 && self.historyArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无数据" offset:0];
        }
    }];
}

//一键复制
-(void)copyMedicinePlanAction:(UIButton *)sender{
    self.hasEdit = YES;
    NSInteger index = sender.tag-1000;
    NSDictionary *tempDic = self.historyArray[index];
    [RequestUtil withPOST:@"/doctor/medical_advice.medical_advice/AdviceMedicineCopy" parameters:@{@"advice_id":self.adviceid,@"record_id":LGNSString(tempDic[@"record_id"]),@"source_type":LGNSString(tempDic[@"source_type"])} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [self requestData];
        }
    } error:^(NSError *error) {
        
    }];
}

//添加药物
-(void)addButtonAction{
    self.hasEdit = YES;
    LGAddMedicineController *controller = [[LGAddMedicineController alloc]init];
    controller.patientid = self.patientid;
//    controller.followid = self.followid;
//    controller.adviceid = self.adviceid;
    [self.navigationController pushViewController:controller animated:YES];
}

-(void)medicineChanged:(NSDictionary *)dataDic type:(NSString *)type{
    if([type isEqualToString:@"delete"] || [type isEqualToString:@"stop"]){
        NSString *action = [type isEqualToString:@"delete"]?@"/doctor/medical_advice.medical_advice/deleteMedicine":@"/doctor/medical_advice.medical_advice/stopMedicine";
        [RequestUtil withPOST:action parameters:@{@"advice_id":self.adviceid,@"medicine_id":LGNSString(dataDic[@"medicine_id"])} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [self requestData];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:LGErrorMessage offset:0];
        }];
    }else if ([type isEqualToString:@"edit"]){
        LGAddMedicineController *controller = [[LGAddMedicineController alloc]init];
        controller.patientid = self.patientid;
//        controller.followid = self.followid;
//        controller.adviceid = self.adviceid;
//        controller.dataDic = dataDic;
        [self.navigationController pushViewController:controller animated:YES];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.historyArray.count+2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return self.dataArray.count;
    }else if (section>1){
        NSArray *tempArray = self.historyArray[section-2][@"medicines"];
        return tempArray.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        LGAdviceMedicineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"medicineCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(self.dataArray.count == 1){
            cell.type = @"single";
        }else if (indexPath.row == 0){
            cell.type = @"top";
        }else if (indexPath.row == self.dataArray.count-1){
            cell.type = @"bottom";
        }else{
            cell.type = @"middle";
        }
        cell.dataDic = self.dataArray[indexPath.row];
        return cell;
    }else if (indexPath.section>1){
        NSArray *tempArray = self.historyArray[indexPath.section-2][@"medicines"];
        LGAdviceRecordMedicineCell *medicineCell = [tableView dequeueReusableCellWithIdentifier:@"recordCell" forIndexPath:indexPath];
        medicineCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(tempArray.count == 1){
            medicineCell.type = @"single";
        }else if (indexPath.row == 0){
            medicineCell.type = @"top";
        }else if (indexPath.row == tempArray.count-1){
            medicineCell.type = @"bottom";
        }else{
            medicineCell.type = @"middle";
        }
        medicineCell.sourceType = LGNSString(self.historyArray[indexPath.section-2][@"source_type"]);
        medicineCell.dataDic = tempArray[indexPath.row];
        return medicineCell;
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        //修改药物
        self.hasEdit = YES;
        LGAddMedicineController *controller = [[LGAddMedicineController alloc]init];
        controller.patientid = self.patientid;
//        controller.followid = self.followid;
//        controller.adviceid = self.adviceid;
//        controller.dataDic = self.dataArray[indexPath.row];
        [self.navigationController pushViewController:controller animated:YES];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ((section == 1 && self.historyArray.count>0) || section > 1) {
        return viewPix(30);
    }
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section > 1 && self.historyArray.count>0) {
        //历史用药
        LGMedicineSectionHeader *headerView = [[LGMedicineSectionHeader alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(30))];
        headerView.dataDic = self.historyArray[section-2];
        UIButton *copyBtn = [UIButton buttonWithTitle:@"一键复制" titleFont:LGFontWeight(14, UIFontWeightMedium) textColor:@"#4C87FD" imageName:@""];
        copyBtn.frame = CGRectMake(Screen_W-viewPix(88), 0, viewPix(88), viewPix(30));
        copyBtn.tag = 1000+section-2;
        [copyBtn addTarget:self action:@selector(copyMedicinePlanAction:) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:copyBtn];
        return headerView;
        
    }else{
        CGFloat height = (section == 1 && self.historyArray.count>0)?viewPix(30):0.01;
        UIView *baseView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, height)];
        if(section == 1 && self.historyArray.count>0){
            UILabel *titleLabel = [UILabel lableWithText:@"历史用药方案" colorString:@"#333333" textFont:LGFontWeight(18, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
            titleLabel.frame = CGRectMake(viewPix(20), viewPix(10), viewPix(200), viewPix(20));
            [baseView addSubview:titleLabel];
        }
        return baseView;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return (section == 0)?viewPix(8):0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height = (section == 0)?viewPix(5):0.01;
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, height)];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, 0, Screen_W, self.view.bounds.size.height);
    self.emptyView.frame = self.tableView.frame;
    self.addButton.frame = CGRectMake((Screen_W-viewPix(70))/2.0, self.view.bounds.size.height-bottomSafeBarHeight/3.0-viewPix(100), viewPix(70), viewPix(90));
    [self.addButton setButtonInsetsStyle:LGButtonInsetsStyleTop marginSpace:-5];
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGAdviceMedicineCell class] forCellReuseIdentifier:@"medicineCell"];
        [_tableView registerClass:[LGAdviceRecordMedicineCell class] forCellReuseIdentifier:@"recordCell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = viewPix(116);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(12))];
    }
    return _tableView;
}

-(UIButton *)addButton{
    if(!_addButton){
        _addButton = [UIButton buttonWithTitle:@"" titleFont:LGFont(16) textColor:@"#999999" imageName:@"发送医嘱-添加服药"];
        [_addButton addTarget:self action:@selector(addButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addButton;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
